﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Administration.Catalog.recDebtorSectorhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.UserManagement;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.UserManagement;
using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Administration.Catalog
{

    public class recDebtorSectorhandler : SIPO.Web.BaseHandler
    {

        private recDebtorSectorRepo recDebtorSectorDal = new recDebtorSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recSectorRepo recsectordal = new recSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;
        private recUserSectorRepo recUserSectorDal = new recUserSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("getdatasector"):
                    context.Response.Write(GetDataSector(context));
                    break;
                case ("getdatabydebtor"):
                    context.Response.Write(getdatabydebtor(context));
                    break;
                case ("updatebydebtor"):
                    context.Response.Write(UpdateByDebtor(context, jObj));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recDebtorSector obj = new recDebtorSector();
                obj.DebtorID = (int)jo["DebtorID"];
                obj.SectorID = (int)jo["SectorID"];
                obj.SubSectorID = (int)jo["SubSectorID"];
                obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                obj.IsActive = isActive;
                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;

                recDebtorSectorDal.Save(obj);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }



        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recDebtorSector obj = new recDebtorSector();
                obj.DebtorSectorID = (int)jo["DebtorSectorID"];
                obj.DebtorID = (int)jo["DebtorID"];
                obj.SectorID = (int)jo["SectorID"];
                obj.SubSectorID = (int)jo["SubSectorID"];
                obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                obj.IsActive = isActive;
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                recDebtorSectorDal.Update(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["DebtorSectorID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    recDebtorSectorDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recDebtorSector.Fields.DebtorID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            string field = ((context.Request.Params["field"]) == null ? string.Empty : context.Request.QueryString["field"].ToString());
            string operand = ((context.Request.Params["operand"]) == null ? string.Empty : context.Request.QueryString["operand"].ToString());
            string value = ((context.Request.Params["value"]) == null ? string.Empty : context.Request.QueryString["value"].ToString());

            string parameters = string.Empty;

            if (!string.IsNullOrEmpty(value))
            {
                field = operand.ToLower().Contains("like") ? "LOWER(" + field + ")" : field;
                field = field.ToLower().Contains("date") ? "CONVERT(char(8), " + field + ", 112)" : field;

                var filter = operand.ToLower().Contains("like") ? "'%" + value.ToLower() + "%'" :
                    field.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(value) + "'" : "'" + value + "'"; // TextBox Filter

                parameters = " WHERE " + field + " " + operand + " " + filter;
            }

            int totalCount = 0;
            int totalPages = 0;
            List<recDebtorSector> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recDebtorSectorDal.SelectScalar(SQL.Function.Aggregate.Count, recDebtorSector.Fields.DebtorSectorID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recDebtorSectorDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string GetDataSector(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recDebtorSector.Fields.DebtorID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            string field = ((context.Request.Params["field"]) == null ? string.Empty : context.Request.QueryString["field"].ToString());
            string operand = ((context.Request.Params["operand"]) == null ? string.Empty : context.Request.QueryString["operand"].ToString());
            string value = ((context.Request.Params["value"]) == null ? string.Empty : context.Request.QueryString["value"].ToString());

            string parameters = string.Empty;

            if (!string.IsNullOrEmpty(value))
            {
                field = operand.ToLower().Contains("like") ? "LOWER(" + field + ")" : field;
                field = field.ToLower().Contains("date") ? "CONVERT(char(8), " + field + ", 112)" : field;

                var filter = operand.ToLower().Contains("like") ? "'%" + value.ToLower() + "%'" :
                    field.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(value) + "'" : "'" + value + "'"; // TextBox Filter

                parameters = " WHERE " + field + " " + operand + " " + filter;
            }

            int totalCount = 0;
            int totalPages = 0;
            List<recDebtorSector> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recDebtorSectorDal.SelectScalar(SQL.Function.Aggregate.Count, recDebtorSector.Fields.DebtorSectorID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recDebtorSectorDal.GetListWithoutDebtor(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData WithoutDebtor";
                log.LogMessage = ex.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        public string getdatabydebtor(HttpContext context)
        {
            int DebtorID = 0;
            int.TryParse(context.Request.Params["debtorId"], out DebtorID);

            List<recDebtorSector> list = recDebtorSectorDal.GetListByDebtor(DebtorID);
            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }

        private string UpdateByDebtor(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                int debtorID = Convert.ToInt32(jo["DebtorID"]);
                List<recDebtorSector> debtorSectors = recDebtorSectorDal.GetList().FindAll(x => x.DebtorID == debtorID);

                List<recUserSector> Usersectorss = new List<recUserSector>(); // menampung user sector dari semua debtor sector
                foreach (recDebtorSector debtorsector in debtorSectors)
                {
                    List<recUserSector> usersectors = recUserSectorDal.GetList().FindAll(x => x.DebtorSectorID == debtorsector.DebtorSectorID); // menampung user sector dari setiap debtor sector
                    foreach (recUserSector usersector in usersectors) // memindah tampungan usersector menjadi satu ke Usersectorss
                    {
                        recUserSector UserSector = new recUserSector();
                        UserSector.DebtorSectorID = usersector.DebtorSectorID;
                        UserSector.UserID = usersector.UserID;
                        Usersectorss.Add(UserSector);
                    }
                }
                string[] subSubSectorIds = Convert.ToString(jo["SubSubSectorID"]).Split(',');

                List<recUser> users = new List<recUser>();

                if (Usersectorss.Count > 0)  // cek jika ditemukan relasi
                {
                    List<recDebtorSector> Dbs = new List<recDebtorSector>();
                    foreach (recDebtorSector DebtorSector in debtorSectors)
                    {
                        
                        bool status = false;
                        for (int i = 0; i < subSubSectorIds.Length; i++)
                            {
                                try
                                {
                                    if (DebtorSector.SubSubSectorID == Convert.ToInt32(subSubSectorIds[i])) // cek apakah ada debtor sector yang dihapus
                                    {
                                        status = true;
                                    }
                                }
                                catch
                                { 
                                //do nothing
                                }
                            }
                        if (status == false) // jika dihapus, cek apakah mempunyai usersector
                        {
                            recUserSectorDal.DeleteByDebtorSectorID(DebtorSector.DebtorSectorID); //jika dihapus, hapus juga user sectornya
                            foreach (recUserSector UserSector in Usersectorss)
                            {
                                if (UserSector.DebtorSectorID == DebtorSector.DebtorSectorID)  // jika mempunyai user sector masukkan ke list
                                {
                              
                                    recUser User = new recUser();
                                    User.UserID = UserSector.UserID;
                                    users.Add(User);
                                }
                            }
                        }
                        else // jika tidak dihapus, hilangkan dalam list... agar tidak masuk dalam delete all dibawah
                        {
                            DebtorSector.DebtorSectorID = -1;
                        }
                    }
                }
                debtorSectors.ForEach(delegate(recDebtorSector debtorSector)
                {
                    try
                    {
                        recDebtorSectorDal.Delete(debtorSector.DebtorSectorID);
                    }
                    catch(Exception ex)
                    {
                        helper.IsSuccess = false;
                        helper.Message = ex.Message;
                    }
                  
                });
                recSubSectorRepo subSectorDal = new recSubSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                recSubSubSectorRepo subSubSectorDal = new recSubSubSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                List<recSubSector> subSectors = subSectorDal.GetList(); // Take all data because there's not much data in there!!
                List<recSubSubSector> subSubSectors = subSubSectorDal.GetList(); // Take all data because there's not much data in there!!
                for (int i = 0; i < subSubSectorIds.Length; i++)
                {
                    try
                    {
                        int subSubSectorId = Convert.ToInt32(subSubSectorIds[i]);
                    }
                    catch
                    {
                        break; // data kosong , keluar dari loop
                    }
                    recDebtorSector obj = new recDebtorSector();
                    obj.SubSubSectorID = Convert.ToInt32(subSubSectorIds[i]);
                    var subSubSector = subSubSectors.Find(x => x.SubSubSectorID == obj.SubSubSectorID);
                    if (subSubSector != null)
                        obj.SubSectorID = subSubSector.SubSectorID;
                    var subSector = subSectors.Find(x => x.SubSectorID == obj.SubSectorID);
                    if (subSector != null)
                        obj.SectorID = subSector.SectorID;
                    obj.CreatedBy = base.UserLoggedIn;
                    obj.CreatedDate = DateTime.Now;
                    obj.DebtorID = (int)jo["DebtorID"];
                    obj.IsActive = true;
                    try
                    {
                        recDebtorSectorDal.Save(obj);
                    }
                    catch{ 
                    //do nothing, id yang dihapus akan dimasukkan kembali, menyebabkan uniqe key error
                    }
                }
                if (users.Count > 0) // jika ada debtorsector yang mempunyai usersector terhapus lakukan ini
                {
                    recUserRepo recUserDal = new recUserRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);   
                    string User = string.Empty;
                    int i = 0;
                    foreach (recUser user in users)
                    { 
                        if (i == 0)
                        {
                            User += user.UserID.ToString();
                            i++;
                        }
                        else {
                            User += ',' + user.UserID.ToString();
                        }
                    }
                    List<recUser> Users = recUserDal.GetList(-1, -1, "", "", "where a.userid in ("+User+")"); // ambil data user, yang sector nya perlu diatur ulang
                    i = 0;
                    User = string.Empty;
                    foreach (recUser user in Users)
                    {
                        if (i == 0)
                        {
                            User += user.UserName;
                            i++;
                        }
                        else
                        {
                            User += ',' + user.UserName;
                        }
                    }
                    helper.IsSuccess = true;
                    helper.Message = "Data berhasil disimpan !\nAtur ulang sektor untuk user dengan nama : " + User +" !";
                }
                else
                {
                    helper.IsSuccess = true;
                    helper.Message = "Data berhasil disimpan!";
                }
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update By Debtor";
                log.LogMessage = helper.Message;
                log.LogSource = "recDebtorSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

    }

}